<?php
class Users extends CI_Controller {

    public function __construct()
	{
        parent::__construct();
		$this->load->model('user_model');
		$this->load->library('HybridAuthLib');
		$member = $this->session->userdata('user');
		$this->is_login=$member['logged_in'];
		$this->memberid=$member['userid'];
		$this->membername=$member['firstname'];
		ini_set('memory_limit', '96M');
		ini_set('upload_max_filesize', '96M');
		ini_set('post_max_size', '96M');
		
    }
	public function send_mail($to,$subject,$message)
	{
		$settingdata=$this->general_model->select_val("setting","*","id = 1");
		/*$config=Array(
			"protocol"=>"smtp",
			"smtp_host"=>"ssl://smtp.gmail.com",
			"smtp_port"=>465,
			"smtp_user"=>"niranjannsahoo@gmail.com",
			"smtp_pass"=>"paikarapursibu"
		);
		$this->load->library('email',$config);*/
		$this->load->library('email');
		$this->email->set_mailtype("html");
		$this->email->set_newline("\r\n");
		$this->email->from($settingdata['notification_email'],$settingdata['site_name']);
		$this->email->reply_to($settingdata['notification_email'], $settingdata['site_name']);	
		$this->email->to($to);		
		$this->email->subject($subject);		
		$this->email->message($message);
		$this->email->send();
	}
	public function index()
	{
		
	}
	public function verify($userid,$rand)
	{
		$check=$this->general_model->count_row("users","userid = '".$userid."' and activation_code = '".$rand."' and activated = 0");
		if($check==1)
		{
			$updatedata=array("activated"=>1);
			$this->general_model->update("users",$updatedata,"userid = ".$userid);
			$this->session->set_flashdata('message', '<p class="success">Thanks for Confirmation! Your account activated,You can login your account.</p>');
		}
		else
		{
			$this->session->set_flashdata('message', '<p class="success">Confirmation Error! We are sorry but your login name/registration stamp is wrong or you have already confirmed! .</p>');
		}
		redirect(BASE_URL);
	}
	public function login()
	{
		
		if($this->input->server('REQUEST_METHOD') === 'POST')
		{
			$query = $this->user_model->validateuser();
			if($query) // if the user's credentials validated...
			{
				redirect(BASE_URL);
			}
			else 
			{
				$this->session->set_flashdata('message', 'That email/password combination does not exist');
				redirect(BASE_URL.'users/login');
			}
		}
		
		
		$this->template->content->view('front/login');
		$this->template->publish();
	}
	public function signup()
	{
		
		if ($this->input->server('REQUEST_METHOD') === 'POST' && $this->validateRegistrationForm())
		{
			$rand=random_string('unique');
			$registrationdata=array(
						"groupid"=>3,
						"group_type"=>'USER',
						"firstname"=>$this->input->post('firstname'),
						"lastname"=>$this->input->post('lastname'),
						"email"=>$this->input->post('email'),
						"password"=>md5($this->input->post('password')),
						"activation_code"=>$rand,
						"date_added"=>date('Y-m-d H:i:s')
						);
			$userid=$this->general_model->insert("users",$registrationdata);
			
			/*basic Zap information*/
			$basicdata=array(
						"userid"=>$userid,
						"firstname"=>$this->input->post('firstname'),
						"lastname"=>$this->input->post('lastname'),
						"email"=>$this->input->post('email'),
						"date_added"=>date('Y-m-d H:i:s')
						);
			$zapuserid=$this->general_model->insert("zap_member",$basicdata);
			
			/*zap setting informatiom */
			$settingdata=array(
						"userid"=>$userid,
						"profile_privacy"=>"Only Me",
						"date_added"=>date('Y-m-d')
						);
			$zapsettingid=$this->general_model->insert("zap_setting",$settingdata);
			
			/*mail verification code*/
			$m_message="Dear ".$this->input->post('firstname')." ".$this->input->post('lastname').", <br /><br />";
			$m_message.="Thanks for Registering! <br /><br />";
			$m_message.="Now you should go the link to activate your membership account:";
			$m_message.="<a href=".base_url('users/verify')."/".$userid."/".$rand.">Activate Now</a> <br /><br />";
			$m_message.="Your Username is :".$this->input->post('email')."<br />";
			$m_message.="Your Password is :".$this->input->post('password')."<br /><br />";
			$m_message.="Thank you!";
			//send email
			$this->send_mail($this->input->post('email'),'Registration Verification: Zap',$m_message);
			$this->session->set_flashdata('message', '<p class="success">Thanks for signing up! Please Check your mail and activate your account.</p>');
			redirect(BASE_URL.'users/signup');	
		}
		$this->template->content->view('front/signup');
		$this->template->publish();
	}
	public function forgotpassword()
	{
		if($this->general_model->loggedin("user") == FALSE)
		{
			//redirect(BASE_URL);
		}
		$userid=$this->memberid;
		if($this->input->server('REQUEST_METHOD') === 'POST')
		{
			$userdata=array("password"=>md5($this->input->post('password')));
			$this->general_model->update('users',$userdata,"userid = ".$userid);
			$this->session->set_flashdata('message', '<p class="success">Password Changed successfully</p>');
			redirect(BASE_URL);
		}
		$this->template->content->view('front/forgotpassword');
		$this->template->publish();
	}
	public function logout()
	{
		$this->user_model->logout();
		redirect(BASE_URL);
	}
	public function resetpassword()
	{
		$chars = "abcdefghijkmnopqrstuvwxyz023456789";
		$i = 0;
		$pass = '' ;

		// Randomly string together a 7 character password
		while ($i <= 7) 
		{
			$num = rand(0, 33);
			$tmp = $chars[$num];
			$pass .= $tmp;
			$i++;
		}
		
		$m_message="Your Zap Password has been reset<br />";
		$m_message.="Your new password is :".$pass;
		
		$count=$this->general_model->count_row("users","email ='".$this->input->post('pemail')."'");
		if($count>=1)
		{
			//send email
			$this->send_mail($this->input->post('pemail'),'Password Reset',$m_message);
			
			$resetdata=array(
								"email"=>$this->input->post('pemail'),
								"password"=>md5($pass)
								);
			$this->general_model->update("users",$resetdata,"email = '".$this->input->post('pemail')."'");				
			$this->session->set_flashdata('message', '<p class="success">Please Check your mail and your password has been reset.</p>');
		}
		else
		{
			$this->session->set_flashdata('message', '<p class="success">Sorry This email does not exist.</p>');
		}
		redirect(BASE_URL);
	}
	public function changepassword()
	{
		if($this->general_model->loggedin("user") == FALSE)
		{
			redirect(BASE_URL);
		}
		$userid=$this->memberid;
		if($this->input->server('REQUEST_METHOD') === 'POST')
		{
			$userdata=array("password"=>md5($this->input->post('password')));
			$this->general_model->update('users',$userdata,"userid = ".$userid);
			$this->session->set_flashdata('message', '<p class="success">Password Changed successfully</p>');
			redirect(BASE_URL);
		}
		
		$data['addmate']=$this->general_model->select_val("addmate_basic","*","userid = ".$userid);
		$this->template->content->view('cms/changepassword',$data);
		$this->template->publish();
	}
	public function settings()
	{
		if($this->general_model->loggedin("user") == FALSE)
		{
			redirect(BASE_URL);
		}
		$data['zapmember']=$this->general_model->get_join2table("zap_member","users","*","zap_member.userid=users.userid","zap_member.userid = ".$this->memberid);
		$ptime1 = new DateTime($data['zapmember']['password_modified']);
		$ptime2 = new DateTime();
		$interval = $ptime1->diff($ptime2);
		$data['password_time']=$interval->format('%a days');
		$data['settingmenu']=1;
		$this->template->content->view('front/settings',$data);
		$this->template->publish();
	}
	public function editsettings()
	{
		if($this->general_model->loggedin("user") == FALSE)
		{
			redirect(BASE_URL);
		}
		if ($this->input->server('REQUEST_METHOD') == 'POST')
		{
			//echo $this->input->server('REQUEST_METHOD');
			$count=$this->general_model->count_row('zap_member','username ='."'".$this->input->post('username')."' and userid =".$this->memberid);
			if(!$count)
			{
				if($this->validateSettingForm())
				{
					$settingdata=array(
								"firstname"=>$this->input->post('firstname'),
								"lastname"=>$this->input->post('lastname'),
								"username"=>$this->input->post('username'),
								"email"=>$this->input->post('email'),
								"date_modified"=>date('Y-m-d H:i:s')
								);
					$this->general_model->update('zap_member',$settingdata,"userid = ".$this->memberid);
					$userdata=array(
								"firstname"=>$this->input->post('firstname'),
								"lastname"=>$this->input->post('lastname'),
								"email"=>$this->input->post('email'),
								"date_modified"=>date('Y-m-d H:i:s')
								);
					$this->general_model->update('users',$userdata,"userid = ".$this->memberid);
				}
				
			}
			else
			{
				
				$settingdata=array(
								"firstname"=>$this->input->post('firstname'),
								"lastname"=>$this->input->post('lastname'),
								"email"=>$this->input->post('email'),
								"date_modified"=>date('Y-m-d H:i:s')
								);
				$this->general_model->update('zap_member',$settingdata,"userid = ".$this->memberid);
				$userdata=array(
								"firstname"=>$this->input->post('firstname'),
								"lastname"=>$this->input->post('lastname'),
								"email"=>$this->input->post('email'),
								"date_modified"=>date('Y-m-d H:i:s')
								);
				$this->general_model->update('users',$userdata,"userid = ".$this->memberid);
				
			}
			if($this->input->post('password')!='')
			{
				$passworddata=array(
							"password"=>md5($this->input->post('password')),
							"password_modified"=>date('Y-m-d H:i:s')
							);
				$this->general_model->update('users',$passworddata,"userid = ".$this->memberid);
				
			}
			$this->session->set_flashdata('message', '<p class="success">Save Changed successfully</p>');
			redirect(BASE_URL.'users/settings');
		}
		$data['zapmember']=$this->general_model->get_join2table("zap_member","users","*","zap_member.userid=users.userid","zap_member.userid = ".$this->memberid);
		$data['settingmenu']=1;
		$this->template->content->view('front/editsettings',$data);
		$this->template->publish();
	}
	public function privacy()
	{
		if($this->general_model->loggedin("user") == FALSE)
		{
			redirect(BASE_URL);
		}
		if ($this->input->server('REQUEST_METHOD') == 'POST')
		{
			$settingdata=array(
								"profile_privacy"=>$this->input->post('profile_privacy'),
								"date_added"=>date('Y-m-d')
								);
			$this->general_model->update('zap_setting',$settingdata,"userid = ".$this->memberid);
			$this->session->set_flashdata('message', '<p class="success">Save Changed successfully</p>');
			redirect(BASE_URL.'users/privacy');		
		}
		$data['zapmember']=$this->general_model->get_join2table("zap_member","users","*","zap_member.userid=users.userid","zap_member.userid = ".$this->memberid);
		$data['settingmenu']=1;
		$data['zapsetting']=$this->general_model->select_val("zap_setting","*","userid = ".$this->memberid);
		
		$this->template->content->view('front/privacy',$data);
		$this->template->publish();
	}
	public function socialsettings()
	{
		if($this->general_model->loggedin("user") == FALSE)
		{
			redirect(BASE_URL);
		}
		$data['user_profile']=array();
		
		try
		{
			$connected_adapters_list = $this->hybridauthlib->getConnectedProviders(); 
			//print_r($connected_adapters_list);
			foreach( $connected_adapters_list as $adapter_id )
			{
				$adapter = $this->hybridauthlib->getAdapter($adapter_id);
				
				$data['user_profile'][$adapter_id] = $adapter->getUserProfile();
			}
		}
		catch(Exception $e)
		{
			$error = 'Unexpected error';
			//echo $e->getCode();
			switch($e->getCode())
			{
				case 0 : $error = 'Unspecified error.'; break;
				case 1 : $error = 'Hybriauth configuration error.'; break;
				case 2 : $error = 'Provider not properly configured.'; break;
				case 3 : $error = 'Unknown or disabled provider.'; break;
				case 4 : $error = 'Missing provider application credentials.'; break;
				case 5 : log_message('debug', 'controllers.HAuth.login: Authentification failed. The user has canceled the authentication or the provider refused the connection.');
				         //redirect();
				         if (isset($service))
				         {
				         	log_message('debug', 'controllers.HAuth.login: logging out from service.');
				         	$service->logout();
				         }
				         show_error('User has cancelled the authentication or the provider refused the connection.');
				         break;
				case 6 : $error = 'User profile request failed. Most likely the user is not connected to the provider and he should to authenticate again.';
				         break;
				case 7 : $error = 'User not connected to the provider.';
				         break;
			}

			if (isset($service))
			{
				$service->logout();
			}

			log_message('error', 'controllers.HAuth.login: '.$error);
			//show_error('Error authenticating user.');
		}
		
		$data['frontmenu']=1;
		$data['zapmember']=$this->general_model->get_join2table("zap_member","users","*","zap_member.userid=users.userid","zap_member.userid = ".$this->memberid);
		$data['socialsetting']=$this->general_model->select_val("zap_socialsetting","*","userid =".$this->memberid);
		//$data['facebook']=unserialize($socialsetting['Facebook']);
		
		$this->template->content->view('front/socialmedia',$data);
		$this->template->publish();
	}
	public function newssettings()
	{
		if($this->general_model->loggedin("user") == FALSE)
		{
			redirect(BASE_URL);
		}
		if ($this->input->server('REQUEST_METHOD') == 'POST')
		{
			$this->general_model->delete_row("zap_member_newsfeed","userid =".$this->memberid);
			$newsfeeddata=$this->input->post('newsfeed');
			
			if(!empty($newsfeeddata))
			{
				
				foreach ($newsfeeddata as $newsfeed)
				{
					$news_feed=array(
							"userid"=>$this->memberid,
							"news_name"=>$newsfeed['news_name'],
							"news_url"=>$newsfeed['news_url'],
							"news_status"=>isset($newsfeed['news_status'])?1:0,
							"date_added"=>date('Y-m-d')		
					);
					$this->general_model->insert("zap_member_newsfeed",$news_feed);
				}
			}
			$this->session->set_flashdata('message', '<p class="success">update successfully</p>');
			redirect("users/newssettings");
		}
		//$data['allnewsfeed'] = $this->general_model->select('zap_newsfeed','*','news_status = 1');
		$data['zapnewsfeed'] = $this->general_model->select('zap_member_newsfeed','*','userid = '.$this->memberid);
		$data['settingmenu']=1;
		$data['zapmember']=$this->general_model->get_join2table("zap_member","users","*","zap_member.userid=users.userid","zap_member.userid = ".$this->memberid);
		
		$this->template->content->view('front/newssettings',$data);
		$this->template->publish();
	}
	public function profilepicture()
	{
		if($this->general_model->loggedin("user") == FALSE)
		{
			redirect(BASE_URL);
		}
		if($this->input->server('REQUEST_METHOD') === 'POST')
		{
			
			if($_FILES)
			{
				//echo ini_get("upload_max_filesize");
				//print_r($_FILES);
				$this->load->library('upload');
				/*main image upload*/
				$configmain = array(
								'allowed_types' => '*', 
								'upload_path' => FCPATH . 'assets/uploads/images/zap', 
								'max_size' => 2097152,
								'overwrite' => False, 
								'file_name' => $this->memberid .'_z'
								);
				$this->upload->initialize($configmain); 
				if ($this->upload->do_upload('photo'))
				{
					$data = array('upload_data' => $this->upload->data());
					//print_r($data);	
					$_POST['photo'] = $data['upload_data']['file_name'];
					$updatedata=array("photo"=>$_POST['photo']);
				
					$this->general_model->update('zap_member',$updatedata,'userid = '.$this->memberid);
					
					//to create thumbnail
					$config = array(
								'source_image' => $data['upload_data']['full_path'], //get original image
								'new_image' => FCPATH . 'assets/uploads/.thumbs/images/zap/', //save as new image //need to create thumbs first
								'maintain_ratio' => true, 
								'width' => 200,
								'height' =>250   
							);
				 
					$this->load->library('image_lib'); 
					$this->image_lib->clear();
					$this->image_lib->initialize($config);
					$this->image_lib->resize();//load library
					 
				}
			}
			$this->session->set_flashdata('message', '<p class="success">Profile Picture successfully Changed</p>');
			redirect(BASE_URL.'users/profilepicture');
		}
		$data['settingmenu']=1;
		$data['zapmember']=$this->general_model->get_join2table("zap_member","users","*","zap_member.userid=users.userid","zap_member.userid = ".$this->memberid);
		
		$this->template->content->view('front/profilepicture',$data);
		$this->template->publish();
	}
	public function postmedia()
	{
		if($this->general_model->loggedin("user") == FALSE)
		{
			redirect(BASE_URL);
		}
		try
		{
			$data['connected_list']  = $this->hybridauthlib->getConnectedProviders(); 
			
		}
		catch( Exception $e )
		{
			echo "Ooophs, we got an error: " . $e->getMessage();

			echo " Error code: " . $e->getCode();

			echo "<br /><br />Please try again.";

			echo "<hr /><h3>Trace</h3> <pre>" . $e->getTraceAsString() . "</pre>"; 
		}
		if($this->input->server('REQUEST_METHOD') === 'POST')
		{
			$facebook= $this->input->post('facebook');
			$twitter= $this->input->post('twitter');
			$instagram= $this->input->post('instagram');
			$youtube= $this->input->post('youtube');
			$snapchat= $this->input->post('snapchat');
			$tumblr= $this->input->post('tumblr');
			$data['media']='';
			$data['mtype']='';
			$data['type']='';
			$social_user='zap';
			if($facebook)
			$social_user=$facebook;
			if($twitter)
			$social_user.=','.$twitter;
			if($instagram)
			$social_user.=','.$instagram;
			if($youtube)
			$social_user.=','.$youtube;
			if($snapchat)
			$social_user.=','.$snapchat;
			if($tumblr)
			$social_user.=','.$tumblr;
			
			
			$messagedata=array(
						"userid"=>$this->memberid,
						"post_desc"=>$this->input->post('message'),
						"social_user"=>$social_user,
						"date_added"=>date('Y-m-d H:i:s'),
						"status"=>1);
			$postid=$this->general_model->insert('zap_post',$messagedata);
			$updatepostid=$this->general_model->update('zap_post',array("postid"=>$postid),"id =".$postid);
			if($_FILES)
			{
			
				$data['mtype']=current(explode("/",$_FILES['photo']['type']));
				$_POST['photo'] = $_FILES['photo']['name'];
				$data['media']=	$_FILES['photo']['tmp_name'];
				if($data['mtype']=="video")
				{
					$updatedata=array("media"=>$_POST['photo'],
									"media_type"=>$data['mtype']);
				
					$this->general_model->update('zap_post',$updatedata,'id = '.$postid);
					
				}
				else
				{		
					$this->load->library('upload');
					/*main image upload*/
					$configmain = array(
									'allowed_types' => '*', 
									'upload_path' => FCPATH . 'assets/uploads/media/', 
									'max_size' => 2097152,
									'overwrite' => false, 
									'file_name' => $this->memberid.'_m'
									);
					//print_r($configmain);
					$this->upload->initialize($configmain); 
					if ($this->upload->do_upload('photo'))
					{
						$data = array('upload_data' => $this->upload->data());
						//print_r($data);
						$data['media']=base_url().'assets/uploads/media/'.$data['upload_data']['file_name'];
						$data['mtype']=current(explode("/",$data['upload_data']['file_type']));
						$data['type']=$data['upload_data']['file_type'];
						$_POST['photo'] = $data['upload_data']['file_name'];
						
						$updatedata=array("media"=>$_POST['photo'],
										"media_type"=>$data['mtype']);
					
						$this->general_model->update('zap_post',$updatedata,'id = '.$postid);
						//to create thumbnail
						$config = array(
									'source_image' => $data['upload_data']['full_path'], //get original image
									'new_image' => FCPATH . 'assets/uploads/.thumbs/media', //save as new image //need to create thumbs first
									'maintain_ratio' => true,
									'width' => 200,
									'height' =>280   
								);
					 
						$this->load->library('image_lib', $config); //load library
						$this->image_lib->resize(); //do whatever specified in config
						$this->image_lib->clear();
					}
				}
			}
			
			
			try
			{
				if($facebook)
				{
					//$adapter = $this->hybridauthlib->authenticate("Facebook");
					$adapter = $this->hybridauthlib->getAdapter($facebook);
					$adapter->setUserStatus(
							array(
								"message" => $this->input->post('message'),
								'source'=>$data['media'],
								)
								
							);  
				}
				if($twitter)
				{
					//$adapter = $this->hybridauthlib->authenticate("Facebook");
					$adapter = $this->hybridauthlib->getAdapter($twitter);
					if($data['mtype']=="image")
					{
						
						$adapter->setUserStatus($this->input->post('message'),$data['media']);
					}
					else
					{
						$adapter->setUserStatus($this->input->post('message'));  
					}
					//$adapter->setUserStatus();

				}
				if($tumblr)
				{
					//$adapter = $this->hybridauthlib->authenticate("Facebook");
					$adapter = $this->hybridauthlib->getAdapter($tumblr);
					if($data['mtype']=="image") 
					$adapter->setUserStatusPhoto( $data['media']);
					else
					$adapter->setUserStatus($this->input->post('message')); 

				}
				if($snapchat)
				{
					//$adapter = $this->hybridauthlib->authenticate("Facebook");
					$adapter = $this->hybridauthlib->getAdapter($snapchat);
					
					
					if($data['mtype']=="image") 
					$adapter->setUserStatusPhoto($data['media']);
					

				}
				if($youtube)
				{
					//$adapter = $this->hybridauthlib->authenticate("Facebook");
					$adapter = $this->hybridauthlib->getAdapter($youtube);
					//print_r( $adapter->getAccessToken() );
					$videoid=$adapter->direct_upload($data['media']);
					$updatedata=array("mediaid"=>$videoid);
					
					$this->general_model->update('zap_post',$updatedata,'id = '.$postid);
						
				}
				
				$this->session->set_flashdata('message', '<p class="success">Comments successfully Posted</p>');
				redirect(BASE_URL.'users/postmedia');
			}
			catch( Exception $e )
			{
				// if code 8 => Provider does not support this feature
				if( $e->getCode() == 8 ){
					$data['message']= "<b style='color:red'>Error: Provider does not support this feature.</b> Currently only <b>Facebook, MySpace, Twitter, Identica and LinkedIn</b> do support this!
					<br />Please refer to the user guide to know more about each adapters capabilities. <a href='http://hybridauth.sourceforge.net/userguide.html'>http://hybridauth.sourceforge.net/userguide.html</a>";
				}
				else{
					$data['message']= "<b style='color:red'>Well, got an error:</b> " . $e->getMessage();
				} 
			} 
			
		}
		//print_r($data['connected_list']);
		$data['frontmenu']=1;
		$data['zapmember']=$this->general_model->get_join2table("zap_member","users","*","zap_member.userid=users.userid","zap_member.userid = ".$this->memberid);
		
		$this->template->content->view('front/postmedia',$data);
		$this->template->publish();
	}
	public function testpostmedia()
	{
		$adapter = $this->hybridauthlib->getAdapter('Youtube');
		//print_r( $adapter->getAccessToken() );
		$adapter->direct_upload('E:\xampp\htdocs\zap\assets\uploads\media\1.flv');
	}
	public function searchfriends()
	{
		if($this->general_model->loggedin("user") == FALSE)
		{
			redirect(BASE_URL);
		}
		$data['zapuser']=array();
		if($_GET)
		{
			$searchvalue = !empty($_GET['search'])?$_GET['search']:' ';
			
			$this->db->select("*");
			$this->db->from("zap_member");
			$this->db->join("users",'zap_member.userid = users.userid');
			$this->db->order_by('zap_member.userid','ASC');
			$this->db->where("zap_member.userid !=",$this->memberid);
			$this->db->where("users.activated =",1);
			$likequery="(zap_member.firstname LIKE '%$searchvalue%'
						or zap_member.lastname LIKE '%$searchvalue%'
						or zap_member.email LIKE '%$searchvalue%'
						or zap_member.username LIKE '%$searchvalue%')";
			$this->db->where($likequery);
			$data['zapuser'] = $this->db->get()->result_array();
			$i=0;
			foreach($data['zapuser'] as $zapuser)
			{
				$countrequest=$this->general_model->count_row('zap_friend_request','request_to ='."'".$zapuser['userid']."' and status = 0 and request_by = ".$this->memberid);
				$countfriend=$this->general_model->count_row('zap_friends','friend_id ='."'".$zapuser['userid']."' and status = 1 and userid = ".$this->memberid);
				
				if($countrequest>=1)
				{
					$data['zapuser'][$i]['friend_request']=1;
				}
				else
				{
					$data['zapuser'][$i]['friend_request']=0;
				}
				if($countfriend>=1)
				{
					$data['zapuser'][$i]['friend']=1;
				}
				else
				{
					$data['zapuser'][$i]['friend']=0;
				}
				$i++;
			}
		}
		/*echo "<pre>";
		print_r($data['zapuser']);*/
		$data['zapmember']=$this->general_model->select_val("zap_member","*","userid = ".$this->memberid);
		
		$data['frontmenu']=1;
		$this->template->content->view('front/searchfriends',$data);
		$this->template->publish();
	}
	public function newsfeed()
	{
		$this->load->library('cisimplepie');
		if($this->general_model->loggedin("user") == FALSE)
		{
			redirect(BASE_URL);
		}
		$data['zapmember']=$this->general_model->select_val("zap_member","*","userid = ".$this->memberid);
		$zapnewsfeed = $this->general_model->select('zap_member_newsfeed','*','news_status = 1 and userid = '.$this->memberid);
		$feeds = array();
		foreach($zapnewsfeed as $newsfeed)
		{
			$feeds[]=$newsfeed['news_url'];
		}
		foreach ($feeds as $url)
		{
			
			$feed = new cisimplepie();
			$feed->set_feed_url($url);
			$feed->set_cache_location(APPPATH.'cache/');
			$feed->init();
			
			
			//$this->cisimplepie->__destruct(); // Do what PHP should be doing on it's own.
			$data['feeds'][] = $feed;
			unset($feed);
		}			
		//print_r($data['feeds']);
		$data['frontmenu']=1;
		$this->template->content->view('front/newsfeed',$data);
		$this->template->publish();
	}
	public function friend_request()
	{
		$data['zapmember']=$this->general_model->select_val("zap_member","*","userid = ".$this->memberid);
		$data['friendrequest']=$this->general_model->get_jointable("zap_friend_request","zap_member","*","zap_friend_request.request_by=zap_member.userid","zap_friend_request.request_to = ".$this->memberid);
		$data['frontmenu']=1;
		$this->template->content->view('front/friendrequest',$data);
		$this->template->publish();
	}
	public function myfriend()
	{
		$data['zapmember']=$this->general_model->select_val("zap_member","*","userid = ".$this->memberid);
		$data['myfriends']=$this->general_model->get_jointable("zap_friends","zap_member","*","zap_friends.friend_id=zap_member.userid","zap_friends.userid = ".$this->memberid . " and zap_member.activated = 1");
		$data['frontmenu']=1;
		$this->template->content->view('front/myfriend',$data);
		$this->template->publish();
	}
	public function profile($userid)
	{
		if($this->general_model->loggedin("user") == FALSE)
		{
			redirect(BASE_URL);
		}
		$zapsetting=$this->general_model->select_val("zap_setting","*","userid = ".$userid);
		
		switch($zapsetting['profile_privacy'])
		{
			case "Only Me":
			if($this->memberid!=$userid)
			{
				$this->session->set_flashdata('message', '<p class="success">Sorry This Profile is Private. No Can view this profile</p>');
				redirect(BASE_URL);
			}
			break;
			case "Friends":
			$myfriends=$this->general_model->get_jointable("zap_friends","zap_member","*","zap_friends.friend_id=zap_member.userid","zap_friends.userid = ".$this->memberid);
			$myfriendsid=array();
			foreach($myfriends as $friend)
			{
				array_push($myfriendsid,$friend['userid']);
			}
			if($this->memberid==$userid)
			{
				break;
			}
			else if(!in_array($userid,$myfriendsid))
			{
				$this->session->set_flashdata('message', '<p class="success">Sorry This Profile is Private. No Can view this profile</p>');
				redirect(BASE_URL);
			}
			break;
			default:
			break;
			
		}
		$yourfriends=$this->general_model->select("zap_friends","friend_id","userid = ".$userid);
		/*$wherein=array();
		foreach($yourfriends as $friends)
		{
			$wherein[]=$friends['friend_id'];
		}
		$wherein[]=$userid;*/
		$data['membermenu']=1;
		$data['zapmember']=$this->general_model->select_val("zap_member","*","userid = ".$userid. " and activated = 1");
		//$data['comments']=$this->general_model->selectmult_jointable("zap_post","zap_member","*,zap_post.id,zap_post.date_added","zap_post.userid=zap_member.userid","zap_post.userid",$wherein,"zap_post.date_added","DESC");
		if(empty($data['zapmember']))
		{
			redirect(BASE_URL);
		}
		$data['ownzap']=$this->general_model->select_val("zap_member","*","userid = ".$this->memberid);
		$data['comments']=$this->general_model->selectmult_jointableord("zap_post","zap_member","*,zap_post.id,zap_post.date_added","zap_post.userid=zap_member.userid","zap_post.userid =".$userid,"zap_post.date_added","DESC");
		$i=0;
		foreach($data['comments'] as $comment)
		{
			$data['comments'][$i]['comment']=$this->general_model->get_jointable("zap_member","zap_postcomment","*","zap_member.userid=zap_postcomment.userid","zap_postcomment.postid = ".$comment['id']);
			$i++;
		}		
		//print_r($data['zapmember']);
		$this->template->content->view('front/profile',$data);
		$this->template->publish();
	}
	public function latestzap()
	{
		if($this->general_model->loggedin("user") == FALSE)
		{
			redirect(BASE_URL);
		}
		$data['frontmenu']=1;
		$data['zapmember']=$this->general_model->select_val("zap_member","*","userid = ".$this->memberid);
		$myfriends=$this->general_model->select("zap_friends","friend_id","userid = ".$this->memberid);
		$wherein=array();
		foreach($myfriends as $friends)
		{
			$wherein[]=$friends['friend_id'];
		}
		$wherein[]=$this->memberid;
		$like="zap_post.social_user like 'zap'";
		$data['zapposts']=$this->general_model->selectmult_jointablelike("zap_post","zap_member","*,zap_post.id,zap_post.date_added","zap_post.userid=zap_member.userid","zap_post.userid",$wherein,$like,"zap_post.date_added","DESC");
		$i=0;
		foreach($data['zapposts'] as $comment)
		{
			$data['zapposts'][$i]['comment']=$this->general_model->get_jointable("zap_member","zap_postcomment","*","zap_member.userid=zap_postcomment.userid","zap_postcomment.postid = ".$comment['id']);
			$i++;
		}	
		//print_r($data['zapmember']);
		$this->template->content->view('front/latestzap',$data);
		$this->template->publish();
	}
	public function messagebackup($userid)
	{
		if($this->general_model->loggedin("user") == FALSE)
		{
			redirect(BASE_URL);
		}
		
		$data['membermenu']=1;
		$data['zapmember']=$this->general_model->select_val("zap_member","*","userid = ".$userid);
		if($this->input->server('REQUEST_METHOD') === 'POST')
		{
			$messagedata=array(
					"fromid"=>$this->memberid,
					"from"=>$this->membername,
					"toid"=>$this->input->post('toid'),
					"to"=>$this->input->post('to'),
					"message"=>$this->input->post('message'),
					"sent"=>date('Y-m-d H:i:s'),
					"recd"=>0,
					"action"=>0,
					
			);
			$messageid=$this->general_model->insert("chat",$messagedata);
			$this->session->set_flashdata('message', '<p class="success">Your Message Succussfully Sent</p>');
			redirect(BASE_URL.'users/message/'.$userid);
		}
		
		$data['previous_message']=$this->general_model->get_jointable("zap_member","chat","*","zap_member.userid=chat.fromid","(fromid = ".$this->memberid . " and toid = ".$userid .") or fromid = ".$userid ." and toid = ".$this->memberid);
		
		$this->template->content->view('front/message',$data);
		$this->template->publish();
	}
	public function message($userid)
	{
		if($this->general_model->loggedin("user") == FALSE)
		{
			redirect(BASE_URL);
		}
		
		$data['membermenu']=1;
		$data['zapmember']=$this->general_model->select_val("zap_member","*","userid = ".$userid);
		if($this->input->server('REQUEST_METHOD') === 'POST')
		{
			$messagedata=array(
					
					"fromid"=>$this->memberid,
					"toid"=>$this->input->post('toid'),
					"message"=>$this->input->post('message'),
					'label_id'=>0,
					"label"=>'inbox',
					"tostatus"=>1,
					"fromstatus"=>1,
					"openstatus"=>0,
					"date_added"=>date('Y-m-d H:i:s')
					
			);
			$messageid=$this->general_model->insert("zap_mailbox",$messagedata);
			$this->session->set_flashdata('message', '<p class="success">Your Message Succussfully Sent</p>');
			redirect(BASE_URL.'users/message/'.$userid);
		}
		
		
		$this->template->content->view('front/message',$data);
		$this->template->publish();
	}
	public function newmessage()
	{
		if($this->general_model->loggedin("user") == FALSE)
		{
			redirect(BASE_URL);
		}
		$data['frontmenu']=1;
		$data['zapmember']=$this->general_model->select_val("zap_member","*","userid = ".$this->memberid);
		//$data['recentmessage']=$this->general_model->get_jointable("zap_member","chat","*","zap_member.userid=chat.fromid","(fromid = ".$this->memberid . " and toid = ".$userid .") or fromid = ".$userid ." and toid = ".$this->memberid);
		$recentmessageid=$this->general_model->selectdistinct('chat',"fromid","toid = ".$this->memberid);
		//print_r($recentmessageid);
		$data['recentmessage']=array();
		foreach($recentmessageid as $recentmessage)
		{
			$data['recentmessage'][]=$this->general_model->get_join2table("zap_member","chat","*","zap_member.userid=chat.fromid","fromid = ".$recentmessage['fromid'] ." and toid = ".$this->memberid .' order by sent DESC limit 0,1');
			$updatedata=array("viewed_message"=>1);
			$this->general_model->update("chat",$updatedata,"fromid =".$recentmessage['fromid'] . " and toid = ".$this->memberid);
		}
		/*echo "<pre>";
		print_r($data['recentmessage']);*/
		$this->template->content->view('front/newmessage',$data);
		$this->template->publish();
	}
	public function inbox()
	{
		if($this->general_model->loggedin("user") == FALSE)
		{
			redirect(BASE_URL);
		}
		$data['frontmenu']=1;
		$data['zapmember']=$this->general_model->select_val("zap_member","*","userid = ".$this->memberid);
		$data['inboxmail']=$this->general_model->get_jointable("zap_mailbox","zap_member","*","zap_mailbox.fromid = zap_member.userid","zap_mailbox.toid = ".$this->memberid." and zap_mailbox.tostatus=1 and zap_mailbox.label = 'inbox'");
		//print_r($data['inboxmail']);
		$data['labelmail']=$this->general_model->get_jointable("zap_mailbox","zap_member","*","zap_mailbox.fromid = zap_member.userid","zap_mailbox.toid = ".$this->memberid." and zap_mailbox.tostatus=1 and zap_mailbox.label != 'inbox'");
		
		$data['recentmsgcount']=$this->general_model->count_row("zap_mailbox","toid = ".$this->memberid ." and label_id = 0 and openstatus = 0");
		//echo $data['recentmsgcount'];
		$data['labels']=$this->general_model->select("zap_mailbox_label","*","userid = ".$this->memberid);
		
		$this->template->content->view('front/inbox',$data);
		$this->template->publish();
	}
	public function sentmail()
	{
		if($this->general_model->loggedin("user") == FALSE)
		{
			redirect(BASE_URL);
		}
		$data['frontmenu']=1;
		$data['zapmember']=$this->general_model->select_val("zap_member","*","userid = ".$this->memberid);
		$data['sentmail']=$this->general_model->get_jointable("zap_mailbox","zap_member","*","zap_mailbox.toid = zap_member.userid","zap_mailbox.fromid = ".$this->memberid." and zap_mailbox.fromstatus=1");
		$data['recentmsgcount']=$this->general_model->count_row("zap_mailbox","toid = ".$this->memberid ." and label_id = 0 and openstatus = 0");
		//$data['labelmail']=$this->general_model->get_jointable("zap_mailbox","zap_member","*","zap_mailbox.fromid = zap_member.userid","zap_mailbox.toid = ".$this->memberid." and zap_mailbox.tostatus=1 and zap_mailbox.label != 'inbox'");
		$data['labels']=$this->general_model->select("zap_mailbox_label","*","userid = ".$this->memberid);
		
		$this->template->content->view('front/sentmail',$data);
		$this->template->publish();
	}
	public function message_details($mailid)
	{
		$data['frontmenu']=1;
		$data['zapmember']=$this->general_model->select_val("zap_member","*","userid = ".$this->memberid);
		if($this->uri->segment(3))
		{
			$data['mail']=$this->general_model->get_join2table("zap_mailbox","zap_member","*","zap_mailbox.fromid = zap_member.userid","zap_mailbox.mailid = ".$this->uri->segment(3));
			$updatemail=array("openstatus"=>1);
			$this->general_model->update("zap_mailbox",$updatemail,"mailid = ".$this->uri->segment(3));
		}
		
		$data['recentmsgcount']=$this->general_model->count_row("zap_mailbox","toid = ".$this->memberid ." and label_id = 0 and openstatus = 0");
		
		$this->template->content->view('front/messagedetails',$data);
		$this->template->publish();
	}
	public function trashmail()
	{
		if($this->general_model->loggedin("user") == FALSE)
		{
			redirect(BASE_URL);
		}
		$data['frontmenu']=1;
		$data['zapmember']=$this->general_model->select_val("zap_member","*","userid = ".$this->memberid);
		$data['thrashmail']=$this->general_model->get_jointable("zap_mailbox","zap_member","*","zap_mailbox.fromid = zap_member.userid","(zap_mailbox.toid = ".$this->memberid ." and zap_mailbox.tostatus = 0) or (zap_mailbox.fromid =".$this->memberid ." and zap_mailbox.fromstatus=0)");
		$data['recentmsgcount']=$this->general_model->count_row("zap_mailbox","toid = ".$this->memberid ." and label_id = 0 and openstatus = 0");
		$data['labels']=$this->general_model->select("zap_mailbox_label","*","userid = ".$this->memberid);
		
		$this->template->content->view('front/trashmail',$data);
		$this->template->publish();
	}
	public function chatbox()
	{
		if($this->general_model->loggedin("user") == FALSE)
		{
			redirect(BASE_URL);
		}
		$data['frontmenu']=1;
		$data['zapmember']=$this->general_model->select_val("zap_member","*","userid = ".$this->memberid);
		$data['recentmsgcount']=$this->general_model->count_row("zap_mailbox","toid = ".$this->memberid ." and label_id = 0 and openstatus = 0");
		$recentmessageid=$this->general_model->selectdistinct('chat',"fromid","toid = ".$this->memberid);
		//print_r($recentmessageid);
		$data['chatbox']=array();
		foreach($recentmessageid as $recentmessage)
		{
			$data['chatbox'][]=$this->general_model->get_join2table("zap_member","chat","*","zap_member.userid=chat.fromid","fromid = ".$recentmessage['fromid'] ." and toid = ".$this->memberid .' order by sent DESC limit 0,1');
		}
		$this->template->content->view('front/chatmessage',$data);
		$this->template->publish();
	}
	public function chatdetails($userid)
	{
		if($this->general_model->loggedin("user") == FALSE)
		{
			redirect(BASE_URL);
		}
		$data['frontmenu']=1;
		$data['zapmember']=$this->general_model->select_val("zap_member","*","userid = ".$this->memberid);
		$data['recentmsgcount']=$this->general_model->count_row("zap_mailbox","toid = ".$this->memberid ." and label_id = 0 and openstatus = 0");
		
		
		
		$data['previous_message']=$this->general_model->get_jointable("zap_member","chat","*","zap_member.userid=chat.fromid","(fromid = ".$this->memberid . " and toid = ".$userid .") or fromid = ".$userid ." and toid = ".$this->memberid);
		
		
		$this->template->content->view('front/chatmessagedetails',$data);
		$this->template->publish();
	}
	public function deletemail()
	{
		if ($this->input->post('selected'))
        {
            $selected = $this->input->post('selected');
        }
        else
        {
            $selected = (array) $this->uri->segment(4);
        }
		$updatedata=array("tostatus"=>0);
		$this->general_model->update_rows('zap_mailbox',$updatedata,'mailid',$selected);
		$this->session->set_flashdata('message', '<p class="success">Mail deleted Successfully.</p>');
		redirect(BASE_URL . "users/inbox");
	}
	public function createlabel()
	{
		if($this->general_model->loggedin("user") == FALSE)
		{
			redirect(BASE_URL);
		}
		if($this->input->server('REQUEST_METHOD') === 'POST')
		{
			$labeldata=array(
					
					"userid"=>$this->memberid,
					"label_name"=>$this->input->post('label_name')
					
					
			);
			$labelid=$this->general_model->insert("zap_mailbox_label",$labeldata);
			$this->session->set_flashdata('message', '<p class="success">Label Successfully Created</p>');
			redirect(BASE_URL.'users/inbox');
		}
	}
	public function deleteuser()
	{
		if($this->general_model->loggedin("user") == FALSE)
		{
			redirect(BASE_URL);
		}
		$data['zapmember']=$this->general_model->select_val("zap_member","*","userid = ".$this->memberid);
		
		$rand=random_string('unique');
		$updatedata=array(
				"deletion_code"=>$rand
				);
		$this->general_model->update("users",$updatedata,"userid = ".$this->memberid);
		//$this->general_model->update("zap_member",$updatedata,"userid = ".$this->memberid);
		/*mail verification code*/
			$m_message="Dear ".$data['zapmember']['firstname']." ".$data['zapmember']['lastname'].", <br /><br />";
			$m_message.="Thanks for using Zap-Out! <br /><br />";
			$m_message.="Now you should go the link to deactivate your Zap-out account:";
			$m_message.="<a href=".base_url('users/removeaccountverify')."/".$this->memberid."/".$rand.">Remove Now</a> <br /><br />";
			
			$m_message.="Thank you!";
			//send email
			$this->send_mail($data['zapmember']['email'],'Zapout Account Deactive: Zap',$m_message);
			
		
		$this->session->set_flashdata('message', '<p class="success">Thanks for Using Zap out! Please Check your mail and deactivate your account.</p>');
		//$this->user_model->logout();
		redirect(BASE_URL .'/users/privacy');
	}
	public function removeaccountverify($userid,$rand)
	{
		$check=$this->general_model->count_row("users","userid = '".$userid."' and deletion_code = '".$rand."' and activated = 1");
		if($check==1)
		{
			$updatedata=array("activated"=>0);
			$this->general_model->update("users",$updatedata,"userid = ".$userid);
			$this->general_model->update("zap_member",$updatedata,"userid = ".$userid);
		
			$this->session->set_flashdata('message', '<p class="success">Thanks for Confirmation! Your account deactivated</p>');
		}
		else
		{
			$this->session->set_flashdata('message', '<p class="success">Confirmation Error! We are sorry but your login name/registration stamp is wrong or you have already confirmed! .</p>');
		}
		$this->user_model->logout();
		redirect(BASE_URL);
	}
	public function album($userid="")
	{
		if($this->general_model->loggedin("user") == FALSE)
		{
			redirect(BASE_URL);
		}
		if($userid=="")
		{
			$userid=$this->memberid;
			$data['frontmenu']=1;
		}
		else
		{
			$data['membermenu']=1;
		}
		
		$data['zapmember']=$this->general_model->select_val("zap_member","*","userid = ".$userid);
		$postimage=$this->general_model->select("zap_post","*","userid = ".$userid . " and media_type = 'image'");
		
		$profileimage=$this->get_images('assets/uploads/images/zap',$userid,'profile');
		//$postimage=$this->get_images('assets/uploads/media',$userid,'media');
		//$data['albumimages']=array_merge($profileimage,$postimage);
		$data['albumimages']=$postimage;
		/*echo "<pre>";
		print_r($data['albumimages']);*/
		$this->template->add_package(array('masonry','fbphotobox'));
		
		$this->template->content->view('front/album',$data);
		$this->template->publish();
	}
	public function notifications()
	{
		if($this->general_model->loggedin("user") == FALSE)
		{
			redirect(BASE_URL);
		}
		$data['frontmenu']=1;
		$data['zapmember']=$this->general_model->select_val("zap_member","*","userid = ".$this->memberid);
		
		$recentcomment=$this->general_model->select_ord("zap_postcomment","distinct(postid)","comment_date","DESC","post_userid = ".$this->memberid ." and view_comment = 1");
		$wherein=array();
		foreach($recentcomment as $recent)
		{
			$wherein[]=$recent['postid'];
		}
		$updatedata=array("view_comment"=>0);
		$this->general_model->update("zap_postcomment",$updatedata,"post_userid = ".$this->memberid ." and view_comment = 1");
		if(empty($wherein))
		{
			$data['comments']='';
		}
		else
		{
			$data['comments']=$this->general_model->selectmult_jointable("zap_post","zap_member","*,zap_post.id,zap_post.date_added","zap_post.userid=zap_member.userid","zap_post.postid",$wherein,"zap_post.date_added","DESC");
			$i=0;
			foreach($data['comments'] as $comment)
			{
				
				$data['comments'][$i]['comment']=$this->general_model->selectmult_jointableord("zap_member","zap_postcomment","*","zap_member.userid=zap_postcomment.userid","zap_postcomment.postid = ".$comment['id'],"zap_postcomment.comment_date","DESC");
				$i++;
			}
		}
		$this->template->content->view('front/notification',$data);
		$this->template->publish();
	}
	function get_images($directory = '/',$userid,$category)
    {
        $theme_dir = BASE_URL;

        $file_array = array();
		$this->load->helper('file');
		$files = get_dir_file_info($directory,$top_level_only = TRUE);
		
        foreach ($files as $file)
        {
			
			if (substr($file['name'], 0, strpos($file['name'], '_')) == $userid)
			{
				$file_array[] = array(
					'name'=>$file['name'],
					'path'=>$file['relative_path'].'/'.$file['name'],
					'category'=>$category
				);
			}
        }

        return $file_array;
    }
	public function validateRegistrationForm()
	{
		$registrationrules=array(
			'email' => array(
			'field' => 'email', 
			'label' => 'Email', 
			'rules' => 'trim|required|valid_email|is_unique[users.email]'
			)
		);
		$this->form_validation->set_rules($registrationrules);
		$this->form_validation->set_message('is_unique','This Email already taken');
		$this->form_validation->set_error_delimiters('<label class="error">', '</label>');
		if ($this->form_validation->run() == TRUE)
		{
			return true;
    	}
		else
		{
			return false;
    	}
	}
	public function validateSettingForm()
	{
		$settingrules=array(
			'username' => array(
			'field' => 'username', 
			'label' => 'Username', 
			'rules' => 'trim|alpha_dash|is_unique[zap_member.username]'
			)
		);
		$this->form_validation->set_rules($settingrules);
		$this->form_validation->set_message('is_unique','This username already in use');
		$this->form_validation->set_message('alpha_dash','This username already in use');
		
		$this->form_validation->set_error_delimiters('<label class="error">', '</label>');
		if ($this->form_validation->run() == TRUE)
		{
			return true;
    	}
		else
		{
			return false;
    	}
	}
	
}
?>